//
//  PKLoginViewController.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/8.
//

import RxSwift
import RxCocoa
import SnapKit
import GoogleSignIn
import AuthenticationServices
import SwiftEntryKit
class PKLoginViewController: UIViewController ,NavigationBarConfigurable {
    private let emailTextField = UITextField()
    private let passwordTextField = UITextField()
    private var loginButton = UIButton(type: .system)
    private var registerButton = UIButton(type: .custom)
    let backButton = UIButton(type: .custom)
    let registerLabel = UILabel()
    private let viewModel = PKLoginViewModal(isLoginButtonEnabled: .just(false))
    let googleLoginButton =  PKCustomImageTitleButton()
    let AppleLoginButton = PKCustomImageTitleButton()
    var showBackButton: Bool { true }
    var shouldHideNavigationBar: Bool { true }
    
    var loginSuccess = BehaviorRelay<String>(value: "")
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        setupUI()
        bindViewModel()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updateNavBarVisibility(animated: animated)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        shouldHideNavigationBar { false }
        
//        updateNavBarVisibility(animated: animated)
    }
    
    private func setupUI() {
        view.backgroundColor = .white
        title = "测试"
        backButton.setImage(.init(named: "back"), for: .normal)
        view.addSubview(backButton)
        emailTextField.tintColor = .black
        passwordTextField.tintColor = .black
 
        
        backButton.rx.tap.subscribe { _ in
            self.navigationController?.popViewController(animated: true)
        }.disposed(by: rx.disposeBag)
        
        
        
        
        let titleLabel = UILabel()
        titleLabel.text = "Sign In"
        titleLabel.font = .adaptedBoldFont(size: 22)
        titleLabel.textAlignment = .center
        emailTextField.placeholder = "Email address"
        emailTextField.borderStyle = .roundedRect
        emailTextField.keyboardType = .emailAddress
        
        passwordTextField.placeholder = "Password"
        passwordTextField.borderStyle = .roundedRect
        passwordTextField.isSecureTextEntry = true
        
//        loginButton = normalButton(.system,"Continue", .normal, 16, 8, .black, .white, false)
//        loginButton = PopRippleButton.createRipple(type: .sys,title: "Continue",fontSize: 16,cornerRadius: 8,backgroundColor: .black,tintColor: .white,isEnabled: false)
        loginButton = UIButton.create(type: .system,title: "Continue",fontSize: 16,cornerRadius: 8,backgroundColor: UIColor(hexString: "ee4d34"),tintColor: .white,isEnabled: false)
        registerButton = UIButton.create(type: .system,title: "Sign up",fontSize: 16,cornerRadius: 8,backgroundColor: .white,tintColor: .blue,isEnabled: true)
        
        registerLabel.text = "Don’t have an account?"
        registerLabel.textColor = .gray
        registerLabel.textAlignment = .center
        view.addSubview(registerLabel)
     
        
        
        googleLoginButton.setImage(.init(named: "google"), for: .normal)
        googleLoginButton.setTitle("Sign in Google", for: .normal)
        googleLoginButton.setTitleColor(.black, for: .normal)
        googleLoginButton.layer.borderColor = UIColor.black.cgColor
        googleLoginButton.layer.borderWidth = 1
        googleLoginButton.layer.cornerRadius = 5
        googleLoginButton.clipsToBounds  = true
        
        AppleLoginButton.setImage(.init(named: "Apple"), for: .normal)
        AppleLoginButton.setTitle("Sign in Apple", for: .normal)
        AppleLoginButton.setTitleColor(.black, for: .normal)
        AppleLoginButton.layer.borderColor = UIColor.black.cgColor
        AppleLoginButton.layer.borderWidth = 1
        AppleLoginButton.layer.cornerRadius = 5
        AppleLoginButton.clipsToBounds  = true
        
        
        view.addSubview(emailTextField)
        view.addSubview(passwordTextField)
        view.addSubview(loginButton)
        view.addSubview(titleLabel)
        view.addSubview(registerButton)
        view.addSubview(googleLoginButton)
        view.addSubview(AppleLoginButton)

        googleLoginButton.rx.controlEvent(.touchUpInside).subscribe { _ in
            
            let vc = UIViewController()
            
            
            GIDSignIn.sharedInstance.signIn(withPresenting: vc) { signInResult, error in
                guard  error == nil else { return }
                
                guard let signInResult = signInResult else { return }
                signInResult.user.refreshTokensIfNeeded { user, error in
                      guard error == nil else { return }
                      guard let user = user else { return }

                      let idToken = user.idToken
                      // Send ID token to backend (example below).
                  }
            }
//            GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult ,error in
//        
//                
//                
//            }
        }.disposed(by: rx.disposeBag)

        registerButton.rx.tap.subscribe { _ in
            let register = PKRegisterViewController()
            self.navigationController?.pushViewController(register, animated: true)
            
            
        }.disposed(by: rx.disposeBag)
        
        
        
        backButton.snp.makeConstraints { make in
            make.left.equalTo(ScreenAdapter.x(20))
            make.top.equalTo(DeviceHelper.navigationBarHeight + 20)
            make.width.height.equalTo(ScreenAdapter.x(30))
        }
        titleLabel.snp.makeConstraints { make in
            make.centerY.equalTo(view.snp.centerY).offset(-200)
            make.centerX.equalToSuperview()
        }
        emailTextField.snp.makeConstraints { make in
            make.centerY.equalToSuperview().offset(ScreenAdapter.x(-80))
            make.left.equalTo(ScreenAdapter.x(50))
            make.right.equalTo(-ScreenAdapter.x(50))
            make.height.equalTo(ScreenAdapter.x(44))
        }
        passwordTextField.snp.makeConstraints { make in
            make.top.equalTo(emailTextField.snp.bottom).offset(20)
            make.leading.equalTo(emailTextField)
            make.trailing.equalTo(emailTextField)
            make.height.equalTo(emailTextField.snp.height)
        }
        loginButton.snp.makeConstraints { make in
            make.top.equalTo(passwordTextField.snp.bottom).offset(80)
            make.leading.equalTo(emailTextField)
            make.trailing.equalTo(emailTextField)
            make.height.equalTo(emailTextField.snp.height)
        }
        googleLoginButton.snp.makeConstraints { make in
            make.top.equalTo(loginButton.snp.bottom).offset(20)
            make.left.equalTo(ScreenAdapter.x(50))
            make.width.equalTo(loginButton)
            make.height.equalTo(ScreenAdapter.x(44))
        }
        AppleLoginButton.snp.makeConstraints { make in
            make.top.equalTo(googleLoginButton.snp.bottom).offset(15)
            make.left.equalTo(ScreenAdapter.x(50))
            make.width.equalTo(loginButton)
            make.height.equalTo(googleLoginButton)
        }
        
        registerButton.snp.makeConstraints { make in
            make.bottom.equalTo(-DeviceHelper.bottomSafeAreaHeight - 30)
            make.centerX.equalToSuperview()
            make.width.equalTo(80)
            make.height.equalTo(30)
        }
        registerLabel.snp.makeConstraints { make in
            make.bottom.equalTo(registerButton.snp.top).offset(-10)
            make.centerX.equalToSuperview()
        }

    }
    
    private func bindViewModel() {
        emailTextField.rx.text.orEmpty
            .bind(to: viewModel.email)
            .disposed(by: rx.disposeBag)
        
        passwordTextField.rx.text.orEmpty
            .bind(to: viewModel.password)
            .disposed(by: rx.disposeBag)
        
        viewModel.isLoginButtonEnabled
            .bind(to: loginButton.rx.isEnabled)
            .disposed(by: rx.disposeBag)

        
        loginButton.rx.tap
            .flatMapLatest { [unowned self] in
                self.viewModel.login()
                    .catch { error in
                        self.showError(error.localizedDescription)
                        return Observable.just(false)
                    }
            }
            .filter { $0 }
            .subscribe(onNext: { [weak self] _ in
                self?.showSuccess()
            })
            .disposed(by: rx.disposeBag)
        
        viewModel.userInfo
                   .observe(on: MainScheduler.instance)
                   .subscribe(onNext: { credential in
                       let userId = credential.user
                       let email = credential.email ?? "No email"
                       let fullName = credential.fullName?.givenName ?? "No name"
                       print("登录成功: \(userId), \(email), \(fullName)")
                   })
                   .disposed(by: rx.disposeBag)
        
        
        AppleLoginButton.rx.tap.subscribe { _ in
            let provider = ASAuthorizationAppleIDProvider()
                let request = provider.createRequest()
                request.requestedScopes = [.fullName, .email] // 请求姓名和邮箱
                
                let controller = ASAuthorizationController(authorizationRequests: [request])
                controller.delegate = self
                controller.presentationContextProvider = self
                controller.performRequests()
            
            
            
        }.disposed(by: rx.disposeBag)
        
        
    }
    
    private func showError(_ message: String) {
        let alert = UIAlertController(title: "Login Failed", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
    
    private func showSuccess() {
        let alert = UIAlertController(title: "Success", message: "You are now logged in!", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
    
//        func normalButton(_ buttonType : UIButton.ButtonType,_ title: String,_ type: UIControl.State, _ fontSize: CGFloat, _ cornerRadius: CGFloat,_ color : UIColor, _ tintColor : UIColor,_ enable : Bool) -> UIButton{
//        let button = UIButton(type: buttonType)
//        button.setTitle(title, for: .normal)
//        button.titleLabel?.font = UIFont.systemFont(ofSize: fontSize, weight: .medium)
//        button.layer.cornerRadius = cornerRadius
//        button.backgroundColor = color
//        button.tintColor = tintColor
//        button.isEnabled = enable
//        return button
//    }
    
    
}
extension PKLoginViewController: ASAuthorizationControllerDelegate {
    // 授权成功
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            let userIdentifier = appleIDCredential.user
            let fullName = appleIDCredential.fullName
            let email = appleIDCredential.email
            
            // ⚠️ 只在首次授权时可获取到 fullName 和 email
            // 建议保存 userIdentifier 供下次使用
            print("User ID: \(userIdentifier)")
            if let jsonString = String(data: appleIDCredential.identityToken!, encoding: .utf8){
                print(jsonString)
           
                NetworkManager.shared.requestAuthObject(.appleLogin(client: userIdentifier, token: jsonString), type: PKTokenModal.self, using: NetworkManager.shared.authprovider).subscribe { [self] modal in
                    print(modal)
                    
                    var descriptionString: String
                    //                    var descriptionThumb: String
                    descriptionString = "Login Success"
                    TokenManager.shared.updateAppleUserIdentifier(userIdentifier)
                    TokenManager.shared.updateAppleToken(jsonString)
                
                    TokenManager.shared.logintype = .apple
                    Popup.shared.showNotificationMessage(attributes: Popup.shared.attributes(), title: "Tips", desc: descriptionString, textColor: EKColor(.white))
                    Observable.just(TokenManager.shared.updateToken(modal.access_token))
                        .delay(.seconds(1), scheduler: MainScheduler.instance)
                        .subscribe(onNext: { [self] value in
                            //                            print("1 秒后输出：\(value)")
                            loginSuccess.accept("success")
                            self.navigationController?.popViewController(animated: true)
                        })
                        .disposed(by: rx.disposeBag)
                    
                    
                    
                    
                    
                    
                    
                    
                }onError: { [self] error in
                    loginSuccess.accept("error")
                }onCompleted: {
                    
                }.disposed(by: rx.disposeBag)
                
                
            }
            if let jsonString1 = String(data: appleIDCredential.authorizationCode!, encoding: .utf8){
                print(jsonString1)
                
                
                
            }
        }
    }

    // 授权失败
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        print("Authorization failed: \(error.localizedDescription)")
    }
}

extension PKLoginViewController: ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window!
    }
}
